<?php
declare (strict_types = 1);

namespace app\controller;

use app\model\Admin;
use think\exception\ValidateException;
use think\facade\Session;

/**
 * 认证控制器
 * Class AuthController
 * @package app\controller
 */
class AuthController extends BaseController
{
    /**
     * 登录
     * @return \think\response\Json
     */
    public function login()
    {
        try {
            $data = $this->request->post();
            
            // 验证数据
            $this->validate($data, [
                'username' => 'require',
                'password' => 'require'
            ], [
                'username.require' => '用户名不能为空',
                'password.require' => '密码不能为空'
            ]);

            // 查找管理员
            $admin = Admin::where('username', $data['username'])->find();
            if (!$admin) {
                return $this->error('用户名或密码错误');
            }

            // 验证密码
            if (!$admin->checkPassword($data['password'])) {
                return $this->error('用户名或密码错误');
            }

            // 检查状态
            if ($admin->status != 1) {
                return $this->error('账号已被禁用');
            }

            // 生成token（这里简化处理，实际项目建议使用JWT）
            $token = md5($admin->id . time() . rand(1000, 9999));
            $tokenExpireTime = date('Y-m-d H:i:s', time() + 7200); // 2小时过期
            
            // 更新登录信息和token
            $admin->last_login_time = date('Y-m-d H:i:s');
            $admin->last_login_ip = $this->request->ip();
            
            // 尝试保存token到数据库（如果字段存在）
            try {
                $admin->token = $token;
                $admin->token_expire_time = $tokenExpireTime;
            } catch (\Exception $e) {
                // 如果字段不存在，忽略错误
            }
            
            $admin->save();
            
            // 存储session
            Session::set('admin_id', $admin->id);
            Session::set('admin_token', $token);

            // 获取用户信息
            $permissions = $admin->getPermissions();
            $userInfo = [
                'id' => $admin->id,
                'username' => $admin->username,
                'nickname' => $admin->nickname,
                'email' => $admin->email,
                'phone' => $admin->phone,
                'avatar' => $admin->avatar,
                'status' => $admin->status,
                'roles' => $admin->roles,
                'permissions' => $permissions,
                'permissionList' => $permissions, // 前端期望的字段名
                'menus' => $admin->getMenus()
            ];

            return $this->success([
                'token' => $token,
                'user' => $userInfo
            ], '登录成功');
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 登出
     * @return \think\response\Json
     */
    public function logout()
    {
        try {
            Session::clear();
            return $this->success([], '登出成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 获取当前用户信息
     * @return \think\response\Json
     */
    public function info()
    {
        try {
            // 优先从request中获取adminId（Auth中间件设置的）
            $adminId = $this->request->adminId ?? Session::get('admin_id');
            if (!$adminId) {
                return $this->error('请先登录', 401);
            }

            $admin = Admin::with(['roles.permissions'])->find($adminId);
            if (!$admin) {
                return $this->error('用户不存在', 401);
            }

            // 获取权限和菜单
            $permissions = $admin->getPermissions();
            $menus = $admin->getMenus();

            $userInfo = [
                'id' => $admin->id,
                'username' => $admin->username,
                'nickname' => $admin->nickname,
                'email' => $admin->email,
                'phone' => $admin->phone,
                'avatar' => $admin->avatar,
                'status' => $admin->status,
                'roles' => $admin->roles,
                'permissions' => $permissions,
                'permissionList' => $permissions, // 前端期望的字段名
                'menus' => $menus
            ];

            return $this->success($userInfo);
        } catch (\Exception $e) {
            // 记录详细错误信息
            \think\facade\Log::error('获取用户信息失败: ' . $e->getMessage() . ' 文件: ' . $e->getFile() . ' 行号: ' . $e->getLine());
            return $this->error('获取用户信息失败: ' . $e->getMessage());
        }
    }

    /**
     * 修改密码
     * @return \think\response\Json
     */
    public function changePassword()
    {
        try {
            $adminId = Session::get('admin_id');
            if (!$adminId) {
                return $this->error('请先登录', 401);
            }

            $admin = Admin::find($adminId);
            if (!$admin) {
                return $this->error('用户不存在', 401);
            }

            $data = $this->request->post();
            
            // 验证数据
            $this->validate($data, [
                'old_password' => 'require',
                'new_password' => 'require|length:6,20',
                'confirm_password' => 'require|confirm:new_password'
            ], [
                'old_password.require' => '原密码不能为空',
                'new_password.require' => '新密码不能为空',
                'new_password.length' => '新密码长度为6-20位',
                'confirm_password.require' => '确认密码不能为空',
                'confirm_password.confirm' => '两次密码输入不一致'
            ]);

            // 验证原密码
            if (!$admin->checkPassword($data['old_password'])) {
                return $this->error('原密码错误');
            }

            // 更新密码
            $admin->password = $data['new_password'];
            $admin->save();

            return $this->success([], '密码修改成功');
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 更新个人信息
     * @return \think\response\Json
     */
    public function updateProfile()
    {
        try {
            $adminId = Session::get('admin_id');
            if (!$adminId) {
                return $this->error('请先登录', 401);
            }

            $admin = Admin::find($adminId);
            if (!$admin) {
                return $this->error('用户不存在', 401);
            }

            $data = $this->request->post();
            
            // 验证数据
            $this->validate($data, [
                'nickname' => 'require|length:2,20',
                'email' => 'email',
                'phone' => 'mobile'
            ], [
                'nickname.require' => '昵称不能为空',
                'nickname.length' => '昵称长度为2-20位',
                'email.email' => '邮箱格式不正确',
                'phone.mobile' => '手机号格式不正确'
            ]);

            // 更新信息
            $admin->save([
                'nickname' => $data['nickname'],
                'email' => $data['email'] ?? '',
                'phone' => $data['phone'] ?? '',
                'avatar' => $data['avatar'] ?? ''
            ]);

            return $this->success($admin, '更新成功');
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
}